﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.Account;
using B.S.BasicData.Api.Read.Application.Command.Log;
using B.S.BasicData.Api.Read.Dtos;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfaces;
using MediatR;
using System.Collections.Generic;
using System.Reflection.Metadata;
using System.Transactions;

namespace B.S.BasicData.Api.Read.Application.CommandHandler.Account
{


    public class QueryAccountHandler : IRequestHandler<QueryAccountCommand, ApiPaging<AccountDTO>>
    {
        private readonly IBaseRepository<AccountModel> accRepo;
        private readonly IMapper mapper;
           private readonly IBaseRepository<RoleModel> roleRepo;
            private readonly IBaseRepository<DepartmentModel> departRepo;
           private readonly ILogger<QueryAccountHandler> logger;

        

        public QueryAccountHandler(IBaseRepository<AccountModel> accRepo, IMapper mapper, IBaseRepository<RoleModel> roleRepo, IBaseRepository<DepartmentModel> departRepo, ILogger<QueryAccountHandler> logger)
        {
            this.accRepo = accRepo;
            this.mapper = mapper;
            this.roleRepo = roleRepo;
            this.departRepo = departRepo;
            this.logger = logger;
        }

        public Task<ApiPaging<AccountDTO>> Handle(QueryAccountCommand request, CancellationToken cancellationToken)
        {
            //添加事务
            using (TransactionScope tran = new TransactionScope())

             {
                        ApiPaging<AccountDTO> result = new ApiPaging<AccountDTO>();
                       try
                        {

                   
                           var accounts = accRepo.Query().Result.Where(x => x.IsDeleted == false);
                            var roles = roleRepo.Query().Result;
                            var departments = departRepo.Query().Result;


                         if (!string.IsNullOrEmpty(request.AccountName))
                       {
                           accounts = accounts.Where(x => x.AccountName.Contains(request.AccountName));
                            }
                           if (!string.IsNullOrEmpty(request.RealName))
                         {
                           accounts=accounts.Where(x=>x.RealName.Contains(request.RealName));
                         }
                        if (!string.IsNullOrEmpty(request.Phone))
                             {
                                 accounts = accounts.Where(x => x.Phone == request.Phone);

                              }

                         if (!string.IsNullOrEmpty(request.DepartmentName))
                         {
                                   departments = departments.Where(x => x.DepartName.Contains(request.DepartmentName));
                             }



                           var linq = from a in accounts
                                     join r in roles on a.RoleId equals r.Id
                                    join d in departments on a.DepartmentId equals d.Id

                                      select new AccountDTO
                                        {
                                      Id = a.Id,
                                       AccountName = a.AccountName,
                                          RealName = a.RealName,
                                          Phone = a.Phone,
                                          IDCard = a.IDCard,
                                          RoleId = a.RoleId,
                                          RoleName = r.RoleName,
                                          DepartmentId = a.DepartmentId,
                                          DepartmentName = d.DepartName
                                      };
                        result.TotalCount = linq.Count();//总条数
                        result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);//总页数

                         var models = linq.OrderBy(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();


                       result.Items = mapper.Map<List<AccountDTO>>(models);
                       result.Code = ApiEnums.Success;
                       result.Msg = "分页数据查询成功!";
                   



                    return Task.FromResult(result);



                }
                catch (Exception e)
                {


                    logger.LogError("查询失败=>" + e.Message);

                    throw;
                }


            }
        }
    }
}

          

